const db = require('../db/index')

// 获取后台宠物信息列表
exports.petList = (req, res) => {
  // 每页几条数据
  let pagesize = 5
  // 当前页码数
  let pagenum = (req.query.pagenum - 1) * pagesize
  let datas = []
  const sql = `select * from pet limit ${pagenum},${pagesize}`
  const sql2 = `select count(*) as total from pet `
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    if (results.length < 0) return res.cc('获取后台宠物信息列表失败！')
    ;(datas = results),
      db.query(sql2, (err, result) => {
        if (err) return res.cc(err)
        if (result.length < 0) return res.cc('获取后台宠物信息列表失败！')
        res.send({
          status: 0,
          message: '获取后台宠物信息列表成功！',
          data: datas,
          total: result[0]
        })
      })
  })
}

// 添加宠物信息
exports.insertPet = (req, res) => {
  const sql = `insert into pet set name = ?, sex = ?, place = ?, breed = ?, blood = ?, price = ?, url = ?, sort = ?,features = ?`
  db.query(sql, [req.body.name, req.body.sex, req.body.place, req.body.breed, req.body.blood, req.body.price, req.body.url, req.body.sort, req.body.features], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('新增宠物失败！')
    res.send({
      status: 0,
      message: '新增宠物成功！'
    })
  })
}

// 根据No删除信息
exports.deleteByNo = (req, res) => {
  const sql = `delete from pet where No = ? `
  db.query(sql, req.body.No, (err, results) => {
    // console.log(req.body.No)
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('删除失败！')
    res.cc('删除成功！', 0)
  })
}
